<template>
  <div class="course-ranking-container">
    <!-- 课程选择区域 -->
    <div class="course-selection-section">
      <el-radio-group v-model="selectedCourse" @change="handleCourseChange" size="medium">
        <el-radio-button v-for="course in courseList" :key="course.id" :label="course.courseName">
          {{ course.courseName }}
        </el-radio-button>
      </el-radio-group>
    </div>
    
    <!-- 课程出勤概览 -->
    <div class="overview-section">
      <div class="overview-card" v-loading="overviewLoading">
        <div class="card-header">
          <h2>{{ selectedCourse }} 出勤概览</h2>
          <span class="last-updated">最后更新: {{ formattedUpdateTime }}</span>
        </div>
        <div class="overview-content">
          <div class="chart-container" ref="attendanceChart"></div>
          <div class="stats-container">
            <div class="stat-card present">
              <div class="stat-icon"><i class="el-icon-user"></i></div>
              <div class="stat-content">
                <div class="stat-value">{{ courseStats.presentCount }}</div>
                <div class="stat-label">出勤人次</div>
              </div>
            </div>
            <div class="stat-card absent">
              <div class="stat-icon"><i class="el-icon-user-solid"></i></div>
              <div class="stat-content">
                <div class="stat-value">{{ courseStats.absentCount }}</div>
                <div class="stat-label">缺勤人次</div>
              </div>
            </div>
            <div class="stat-card rate">
              <div class="stat-icon"><i class="el-icon-data-analysis"></i></div>
              <div class="stat-content">
                <div class="stat-value">{{ formatPercentage(courseStats.attendanceRate) }}</div>
                <div class="stat-label">出勤率</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Top 5 学生排名表格 -->
    <div class="ranking-section">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="成绩排名 Top 5" name="score">
          <div class="ranking-card" v-loading="rankingLoading">
            <div class="card-header">
              <h2>{{ selectedCourse }} - 成绩优秀学生</h2>
            </div>
            <div class="ranking-table">
              <el-table :data="topStudentsByScore" style="width: 100%" :row-class-name="tableRowClassName">
                <el-table-column label="排名" width="80" align="center">
                  <template slot-scope="scope">
                    <div class="rank-badge-container">
                      <div :class="['rank-badge', getRankBadgeClass(scope.$index)]">{{ scope.$index + 1 }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
                <el-table-column prop="studentName" label="姓名" width="100"></el-table-column>
                <el-table-column prop="classId" label="班级" width="100"></el-table-column>
                <el-table-column prop="totalScore" label="总分" width="100" sortable>
                  <template slot-scope="scope">
                    <div class="highlight-score">{{ scope.row.totalScore }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="出勤率" min-width="180">
                  <template slot-scope="scope">
                    <el-progress 
                      :percentage="roundPercentage(scope.row.attendanceRate)" 
                      :color="getAttendanceRateColor(scope.row.attendanceRate)"
                      :format="percentFormat"
                      :stroke-width="8">
                    </el-progress>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="出勤率 Top 5" name="attendance">
          <div class="ranking-card" v-loading="rankingLoading">
            <div class="card-header">
              <h2>{{ selectedCourse }} - 出勤优秀学生</h2>
            </div>
            <div class="ranking-table">
              <el-table :data="topStudentsByAttendance" style="width: 100%" :row-class-name="tableRowClassName">
                <el-table-column label="排名" width="80" align="center">
                  <template slot-scope="scope">
                    <div class="rank-badge-container">
                      <div :class="['rank-badge', getRankBadgeClass(scope.$index)]">{{ scope.$index + 1 }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
                <el-table-column prop="studentName" label="姓名" width="100"></el-table-column>
                <el-table-column prop="classId" label="班级" width="100"></el-table-column>
                <el-table-column label="出勤率" width="180">
                  <template slot-scope="scope">
                    <el-progress 
                      :percentage="roundPercentage(scope.row.attendanceRate)" 
                      :color="getAttendanceRateColor(scope.row.attendanceRate)"
                      :format="percentFormat"
                      :stroke-width="8">
                    </el-progress>
                  </template>
                </el-table-column>
                <el-table-column prop="totalScore" label="总分" min-width="100" sortable>
                  <template slot-scope="scope">
                    <div>{{ scope.row.totalScore }}</div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="缺勤率 Top 5" name="absent">
          <div class="ranking-card" v-loading="rankingLoading">
            <div class="card-header">
              <h2>{{ selectedCourse }} - 需要关注的学生</h2>
            </div>
            <div class="ranking-table">
              <el-table :data="topStudentsByAbsent" style="width: 100%" :row-class-name="tableRowClassName">
                <el-table-column label="排名" width="80" align="center">
                  <template slot-scope="scope">
                    <div class="rank-badge-container">
                      <div class="rank-badge absent">{{ scope.$index + 1 }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
                <el-table-column prop="studentName" label="姓名" width="100"></el-table-column>
                <el-table-column prop="classId" label="班级" width="100"></el-table-column>
                <el-table-column label="出勤率" width="180">
                  <template slot-scope="scope">
                    <el-progress 
                      :percentage="roundPercentage(100 - scope.row.attendanceRate)" 
                      :color="getAbsentRateColor(100 - scope.row.attendanceRate)"
                      :format="percentFormat"
                      :stroke-width="8">
                    </el-progress>
                  </template>
                </el-table-column>
                <el-table-column prop="totalScore" label="总分" min-width="100" sortable>
                  <template slot-scope="scope">
                    <div>{{ scope.row.totalScore }}</div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'CourseAttendanceRanking',
  data() {
    return {

      // 静态课程名称列表
      courseList: [
        { id: 1, courseName: 'Hive' },
        { id: 2, courseName: 'Spark' },
        { id: 3, courseName: 'Flink' },
        { id: 4, courseName: 'Hadoop' },
        { id: 5, courseName: 'HBase' },
        { id: 6, courseName: 'Kafka' }
      ],
      selectedCourse: 'Hive', // 默认选中第一个课程
      overviewLoading: false,
      rankingLoading: false,
      activeTab: 'score',
      
      // 课程统计数据
      courseStats: {
        presentCount: 0,
        absentCount: 0,
        attendanceRate: 0,
        lastUpdated: new Date()
      },
      
      // 学生排名数据
      topStudentsByScore: [],
      topStudentsByAttendance: [],
      topStudentsByAbsent: [],
      
      // 图表实例
      attendanceChart: null
    };
  },
  computed: {
    formattedUpdateTime() {
      return new Date(this.courseStats.lastUpdated).toLocaleString('zh-CN');
    }
  },
  mounted() {
    // 初始化默认课程的数据
    if (this.selectedCourse) {
      this.getCourseStats(this.selectedCourse);
      this.getStudentRankings(this.selectedCourse);
    }
    
    // 初始化图表
    this.$nextTick(() => {
      this.initAttendanceChart();
    });
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
    if (this.attendanceChart) {
      this.attendanceChart.dispose();
    }
  },
  methods: {
    // 处理课程变更
    handleCourseChange(courseName) {
      // 切换课程时获取新数据
      this.getCourseStats(courseName);
      this.getStudentRankings(courseName);
    },
    
    // 处理标签页切换
    handleTabChange() {
      // 可以在这里处理切换到不同标签时的逻辑
    },
    
    // 获取课程统计数据 - 与后端API对接
    async getCourseStats(courseName) {
      this.overviewLoading = true;
      
      try {
        // 从后端获取课程的出勤统计数据 - 使用实际API路径
        const response = await this.$request.get(`/courses/${courseName}/attendance`);
        console.log(response+"=----")
       
          this.courseStats = {
            presentCount: response.presentCount || 0,
            absentCount: response.absentCount || 0,
            attendanceRate: response.attendanceRate || 0,
            lastUpdated: response.lastUpdated || new Date()
          };
        
        
        // 更新图表数据
        this.$nextTick(() => {
          this.updateAttendanceChart();
        });
      } catch (error) {
        console.error(`获取课程${courseName}统计数据失败:`, error);
        this.$message.error('获取课程统计数据失败');
        

        this.$nextTick(() => {
          this.updateAttendanceChart();
        });
      } finally {
        this.overviewLoading = false;
      }
    },
    
    
    
    // 获取学生排名数据 - 与后端API对接
    async getStudentRankings(courseName) {
      this.rankingLoading = true;
      try {
        // 使用实际的API路径获取学生排名
        // 成绩排名前5
        const scoreResponse = await this.$request.get(`/courses/${courseName}/top-students`, {
          params: { 
            sortBy: 'score', 
            limit: 5 
          }
        });
        
       
          this.topStudentsByScore = scoreResponse;

      
        // 出勤率排名前5
        const attendanceResponse = await this.$request.get(`/courses/${courseName}/top-students`, {
          params: { 
            sortBy: 'attendance', 
            limit: 5 
          }
        });
        
   
          this.topStudentsByAttendance = attendanceResponse;
        
        
        // 缺勤率排名前5
        const absentResponse = await this.$request.get(`/courses/${courseName}/top-students`, {
          params: { 
            sortBy: 'absent', 
            limit: 5 
          }
        });
        
          this.topStudentsByAbsent = absentResponse;
      } catch (error) {
        console.error(`获取${courseName}学生排名数据失败:`, error);
        this.$message.error('获取学生排名数据失败');
        
  
      } finally {
        this.rankingLoading = false;
      }
    },
    
  
    
    // 初始化出勤率图表
    initAttendanceChart() {
      const chartDom = this.$refs.attendanceChart;
      if (!chartDom) return;
      
      this.attendanceChart = echarts.init(chartDom);
      this.updateAttendanceChart();
    },
    
    // 更新图表数据
    updateAttendanceChart() {
      if (!this.attendanceChart) return;
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 10,
          data: ['出勤', '缺勤']
        },
        color: ['#67C23A', '#F56C6C'],
        series: [
          {
            name: this.selectedCourse + '出勤情况',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'center',
              formatter: () => {
                return `出勤率\n${this.formatPercentage(this.courseStats.attendanceRate)}`;
              },
              fontSize: 16,
              fontWeight: 'bold'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: this.courseStats.presentCount, name: '出勤' },
              { value: this.courseStats.absentCount, name: '缺勤' }
            ]
          }
        ]
      };
      
      this.attendanceChart.setOption(option);
    },
    
    // 调整图表大小
    resizeChart() {
      if (this.attendanceChart) {
        this.attendanceChart.resize();
      }
    },
    
    // 获取排名徽章样式类
    getRankBadgeClass(index) {
      if (index === 0) return 'gold';
      if (index === 1) return 'silver';
      if (index === 2) return 'bronze';
      return '';
    },
    
    // 格式化显示的百分比值
    formatPercentage(value) {
      return value.toFixed(1) + '%';
    },

    // 四舍五入进度条的百分比值
    roundPercentage(value) {
      return Math.round(value * 10) / 10;
    },
    
    // 获取出勤率颜色
    getAttendanceRateColor(rate) {
      if (rate >= 90) return '#67C23A';
      if (rate >= 75) return '#E6A23C';
      return '#F56C6C';
    },
    
    // 获取缺勤率颜色（与出勤率颜色相反）
    getAbsentRateColor(rate) {
      if (rate >= 25) return '#F56C6C';
      if (rate >= 10) return '#E6A23C';
      return '#67C23A';
    },
    
    // 百分比格式化
    percentFormat(percentage) {
      return percentage.toFixed(1) + '%';
    },
    
    // 表格行样式
    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 0) return 'first-row';
      if (rowIndex === 1) return 'second-row';
      if (rowIndex === 2) return 'third-row';
      return '';
    }
  }
}
</script>

<style scoped>
.course-ranking-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  /* 将背景颜色从浅灰色 #f5f7fa 修改为纯白色 #ffffff */
  background-color: #ffffff;
}

.course-selection-section {
  margin-bottom: 20px;
  text-align: center;
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  background-color: white; /* 卡片背景色是白色 */
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  /* 这个边框颜色是 #f0f0f0 (浅灰色)，如果觉得有问题也可以修改 */
  border-bottom: 1px solid #f0f0f0;
}

.card-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.last-updated {
  font-size: 12px;
  color: #909399;
}

.overview-content {
  display: flex;
  height: 300px;
}

.chart-container {
  width: 60%;
  height: 100%;
}

.stats-container {
  width: 40%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  padding: 0 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  color: white;
  gap: 15px;
}

.stat-card.present {
  background-color: #67C23A;
}

.stat-card.absent {
  background-color: #F56C6C;
}

.stat-card.rate {
  background-color: #409EFF;
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  font-size: 20px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
}

.stat-label {
  font-size: 13px;
  opacity: 0.9;
}

.ranking-section {
  margin-top: 20px;
}

.ranking-card {
  background-color: white; /* 卡片背景色是白色 */
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 20px;
}

.ranking-table {
  margin-top: 10px;
}

.rank-badge-container {
  display: flex;
  justify-content: center;
}

.rank-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  font-weight: bold;
  color: white;
  background-color: #909399;
}

.rank-badge.gold {
  background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
  box-shadow: 0 2px 6px rgba(255, 215, 0, 0.3);
}

.rank-badge.silver {
  background: linear-gradient(135deg, #E0E0E0 0%, #B0B0B0 100%);
  box-shadow: 0 2px 6px rgba(176, 176, 176, 0.3);
}

.rank-badge.bronze {
  background: linear-gradient(135deg, #CD7F32 0%, #A05215 100%);
  box-shadow: 0 2px 6px rgba(205, 127, 50, 0.3);
}

.rank-badge.absent {
  background: linear-gradient(135deg, #F56C6C 0%, #C45656 100%);
  box-shadow: 0 2px 6px rgba(245, 108, 108, 0.3);
}

.highlight-score {
  font-weight: 600;
  font-size: 16px;
  color: #F56C6C;
}



@media (max-width: 768px) {
  .overview-content {
    flex-direction: column;
    height: auto;
  }

  .chart-container, .stats-container {
    width: 100%;
  }

  .chart-container {
    height: 250px;
    margin-bottom: 20px;
  }
}
</style>